package cn.example.vip.mall.user.controller;

import cn.example.vip.mall.user.entity.UserInfo;
import cn.example.vip.mall.user.service.UserInfoService;
import cn.example.vip.mall.util.IPUtils;
import cn.example.vip.mall.util.JwtToken;
import cn.example.vip.mall.util.MD5;
import cn.example.vip.mall.util.RespResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录接口
 */
@CrossOrigin
@RestController
@RequestMapping("/user/info")
public class UserInfoController {
	private static final Logger log = LogManager.getLogger(UserInfoController.class);
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private HttpServletRequest request;
	
	/**
	 * 登录服务是否存活
	 * @return
	 */
	@GetMapping
	public RespResult info() {
		return RespResult.ok();
	}
	
	/**
	 * 注册
	 * @param userInfo
	 * @return
	 */
	@PostMapping("/register")
	public RespResult register(@RequestBody UserInfo userInfo) {
		Integer code = userInfoService.userRegister(userInfo);
		// 查询用户
//		UserInfo userInfo1
		return RespResult.ok(code);	// 200 成功
	}
	
	/**
	 * 登录
	 * @param userInfo
	 * @return
	 */
	@PostMapping("/login")
	public RespResult login(@RequestBody UserInfo userInfo) throws Exception {
//		Integer code = userInfoService.userLogin(response, userInfo);
//		return RespResult.ok(code);
		
		// 查询用户
		UserInfo getUser = userInfoService.getById(userInfo.getUsername());
		// 匹配
		if(getUser != null && userInfo.getPassword().equals(getUser.getPassword())) {
			// 封装令牌
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("username", getUser.getUsername());
			dataMap.put("password", getUser.getPassword());
			dataMap.put("roles", getUser.getRoles());
			// 获取并绑定ip,回避重放攻击
			String ip = IPUtils.getIpAddr(request);
			dataMap.put("ip", MD5.md5(ip));	// MD5加密ip
			// 创建令牌
			String token = JwtToken.createToken(dataMap);
			return RespResult.ok(token);	// 200 成功
		}
		return RespResult.error();	// 500 错误
	}
}
